#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/12/28 16:22
# @Author  : Andrewq
# @Site    : nope
# @File    : studyHistoryController.py
# @Software: PyCharm

import datetime

from flask import g, current_app
from sqlalchemy import or_

from ..models import db
from ..models.UserCollectModel import UserCollect
from ..models.UserStudyHistoriesModel import UserStudyHistory
from ..utils import commons
from ..utils.response_code import RET


class studyHistoryController(UserStudyHistory):

    @classmethod
    def get_list(cls, **kwargs):
        code_id = kwargs.get('codeID')
        web_id = kwargs.get('webID')
        infomation_id = kwargs.get('infomationID')
        user_ID = kwargs.get('userID') if kwargs.get("userID") else g.user.user_id
        pre_study_name = kwargs.get('preStudyName')
        time_zone = kwargs.get('timeZone')
        filter_list = []
        filter_list.append(cls.userID == user_ID)
        if code_id:
            filter_list.append(cls.codeID == code_id)
        if web_id:
            filter_list.append(cls.webID == web_id)
        if infomation_id:
            filter_list.append(cls.infomationID == infomation_id)
        if pre_study_name:
            filter_list.append(cls.preStudyName.contains(pre_study_name))
        if time_zone:
            now_time = datetime.datetime.now()
            past_time = datetime.datetime.now() - datetime.timedelta(days=int(time_zone))
            filter_list.append(cls.createTime.between(past_time, now_time))
        try:
            records = db.session.query(cls).filter(*filter_list)

            if not records.first():
                return {'code': RET.NODATA, 'msg': '没有查询到数据', 'data': []}

            back_data = commons.query_to_dict(records.all())

            return {'code': RET.OK, 'msg': '查询数据成功', 'data': back_data}
        except Exception as e:
            current_app.logger.error(e)
            return {'code': RET.DBERR, 'msg': '数据库异常，查询收藏信息失败', 'error': str(e)}

    @classmethod
    def add(cls, **kwargs):
        user_ID = kwargs.get('userID') if kwargs.get("userID") else g.user.user_id
        pre_study_name = kwargs.get('preStudyName')

        filter_list = []
        filter_list.append(cls.userID == user_ID)
        filter_list.append(cls.preStudyName == pre_study_name)
        try:
            record = db.session.query(cls).filter(*filter_list)

            if record.first():
                record.delete()

            Record = UserStudyHistory(
                userID=user_ID,
                preStudyName=pre_study_name,
                preStudyUrl=kwargs.get('preStudyUrl'),
                codeID=kwargs.get('codeID'),
                infomationID=kwargs.get('infomationID'),
                webID=kwargs.get('webID')
            )
            db.session.add(Record)
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            return {'code': RET.DBERR, 'msg': '数据库异常，查询收藏信息失败', 'error': str(e)}

        back_data = commons.query_to_dict(Record)
        return {'code': RET.OK, 'msg': '添加历史记录数据成功', 'data': back_data}

    @classmethod
    def delete(cls, **kwargs):
        user_ID = kwargs.get('userID') if kwargs.get("userID") else g.user.user_id
        pre_study_name = kwargs.get('preStudyName')
        mode = kwargs.get('mode')
        try:
            if mode == 'list':
                data = kwargs.get('data')
                for item in eval(data):
                    filter_list = []
                    filter_list.append(cls.userID == user_ID)
                    filter_list.append(cls.preStudyName == item['data']['preStudyName'])
                    record = db.session.query(cls).filter(*filter_list)
                    if not record.first():
                        continue
                    record.delete()
                    db.session.commit()
                return {'code': RET.OK, 'msg': '删除所有数据成功'}

            if mode == 'single':
                filter_list = []
                filter_list.append(cls.userID == user_ID)
                filter_list.append(cls.preStudyName == pre_study_name)

                record = db.session.query(cls).filter(*filter_list)

                if not record.first():
                    return {'code': RET.NODATA, 'msg': '没有查询到数据', 'data': []}
                back_data = commons.query_to_dict(record.first())
                record.delete()
                db.session.commit()
                return {'code': RET.OK, 'msg': '删除成功', 'data': back_data}
        except Exception as e:
            current_app.logger.error(e)
            return {'code': RET.DBERR, 'msg': '数据库异常，查询收藏信息失败', 'error': str(e)}


